//
//  MyCollectionViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/7.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "MyCollectionViewModel.h"

#import "CommonNewsItemCell.h"

#import "CollectionsListData.h"

@interface MyCollectionViewModel()

@property (nonatomic, readwrite, strong) RACCommand* requestDataCmd;
@property (nonatomic, readwrite, strong) RACCommand* unCollectionCmd;

@property (nonatomic, readwrite, strong) RACCommand* selectCmd;

@end

@implementation MyCollectionViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    self.cellHeight = 94.0f;
    
    self.lastPage = 100;
    self.shouldMultiSections = NO;
    /// viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = YES;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = YES;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = YES;
    
    /// 选中
    self.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath* indexPath)
    {
        @strongify(self);
        
        CommonNewsItemViewModel* cm = self.dataSource[indexPath.row];
        CollectionListData* clistData = cm.data;
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^{
                [subscriber sendNext:clistData];
                [subscriber sendCompleted];
            });
            return nil;
        }];
    }];
    /// 允许并行执行
    self.selectCmd.allowsConcurrentExecution = NO;
    
    self.unCollectionCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        @weakify(self);
        return [[self _requestUnCollectionSignal:input] doNext:^(id x)
        {
            @strongify(self);
            
            NSIndexPath* indexPath = input;
            
            NSMutableArray* copyDatasource = [NSMutableArray arrayWithArray:self.dataSource];
            [copyDatasource removeObjectAtIndex:indexPath.row];
            self.dataSource = copyDatasource;
        }];
    }];
}

- (RACSignal*)_requestUnCollectionSignal:(NSIndexPath*)indexPath
{
    @weakify(self);
    
    CommonNewsItemViewModel* ivm = self.dataSource[indexPath.row];
    
    CollectionListData* clistData = ivm.data;
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
        
        NSString* userID = um.userData.userID;
        NSString* type = @"1";
        NSString* articleID = clistData.articleID;
        
        @weakify(self);
        [[AFNetWorkUtils racPOSTWthURL:url_interface_articlecollect params:interface_param_articlecollect(userID, type, articleID)] subscribeNext:^(id x)
         {
             @strongify(self);
             
             [subscriber sendNext:x[SUCommandSysMessageKey]];
             [subscriber sendCompleted];
             
         } error:^(NSError *error)
         {
             //错误处理
             
             NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"取消收藏失败";
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    @weakify(self)
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        NSDictionary* postData = interface_param_user_collection(um.userData.userID, @(page+1), @(List_PageSize));
        
        @weakify(self);
        return [[AFNetWorkUtils racPOSTWthURL:url_interface_user_collection params:postData] subscribeNext:^(id x)
                {
                    @strongify(self)
                    
                    /// 转化数据
                    @weakify(self);
                    
                    CollectionsListData* cListData = [CollectionsListData modelWithJSON:x];
                    
                    NSArray *viewModels = [cListData.datas.rac_sequence map:^CommonNewsItemViewModel *(CollectionListData* data)
                                           {
                                               @strongify(self);
                                               
                                               CommonNewsItemViewModel *itemViewModel = [[CommonNewsItemViewModel alloc] initWithData:data cellHeight:self.cellHeight];
                                               
                                               return itemViewModel;
                                           }].array;
                    
                    if (self.shouldPullUpToLoadMore)
                    {
                        if (0 == page)
                        {
                            self.dataSource = viewModels;
                        }
                        else
                        {
                            if (self.dataSource == nil)
                            {
                                self.dataSource = viewModels;
                            }
                            else
                            {
                                self.dataSource = [self.dataSource arrayByAddingObjectsFromArray:viewModels];
                            }
                        }
                    }
                    else
                    {
                        self.dataSource = viewModels;
                    }
                    
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                }   error:^(NSError *error) {
                    //错误处理
                    
                    [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
                    [subscriber sendCompleted];
                }
                ];
        
        return nil;
    }];
}

@end
